package webshop.model.bl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import webshop.model.db.Category;
import webshop.model.sf.HibernateUtil;

public class CategoryManager {
	
	public void addCategory(String categoryname) {
		Category category = new Category(categoryname);
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		session.save(category);
		
		session.getTransaction().commit();
	}
	
	public boolean categoryExists(String categoryName) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Category> categoryList = session.createCriteria(Category.class).add(
				Restrictions.eq("name", categoryName).ignoreCase()
				).list();
		
		session.getTransaction().commit();
		
		return categoryList == null || categoryList.size() == 0 ? false : true;
	}
	
	public List<Category> getAllCategories() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Category> categoryList = session.createCriteria(Category.class).list();
		
		session.getTransaction().commit();
		
		return categoryList;
	}
	
	public Category getCategoryById(Integer categoryId) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		
		@SuppressWarnings("unchecked")
		List<Category> categoryList = session.createCriteria(Category.class).add(
				Restrictions.eq("categoryId", categoryId)
				).list();
		
		session.getTransaction().commit();
		
		return categoryList == null || categoryList.size() == 0 ? null : categoryList.get(0);
	}
	
	public void deleteCategory(Integer categoryId) {
		Category category = getCategoryById(categoryId);
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		session.delete(category);
		
		session.getTransaction().commit();
	}

}
